package com.yunkaweilai.android.view.popup;

import android.app.Activity;
import android.support.annotation.IdRes;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.classic.common.MultipleStatusView;
import com.github.lazylibrary.util.StringUtils;
import com.google.gson.Gson;
import com.yunkaweilai.android.R;
import com.yunkaweilai.android.constants.Api;
import com.yunkaweilai.android.interfaces.PopupCouponSelector;
import com.yunkaweilai.android.model.operation.CreateSelectedGoodsModel;
import com.yunkaweilai.android.model.operation.MemberCouponModel;
import com.yunkaweilai.android.model.order.PaymentAmountModel;
import com.yunkaweilai.android.net.HttpRequest;
import com.yunkaweilai.android.net.PostProcess;
import com.yunkaweilai.android.utils.Utils;
import com.yunkaweilai.android.view.MyToast;
import com.zhy.adapter.abslistview.CommonAdapter;
import com.zhy.adapter.abslistview.ViewHolder;

import java.util.ArrayList;

import razerdp.basepopup.BasePopupWindow;

/**
 * 优惠券
 * Created by Administrator on 2017/7/17.
 */

public class MemberCouponPopup extends BasePopupWindow{

    private View popupView;
    private Activity mContext;
    private ArrayList<MemberCouponModel.DataBean.ListBean> list = new ArrayList<>();
    private CommonAdapter<MemberCouponModel.DataBean.ListBean> adapter;
    private PopupCouponSelector popupCouponSelector;
    private ListView idListView;
    private String id;
    private MultipleStatusView idMultipLe;
    private RadioGroup idRgpSelector;
    private RelativeLayout idRlayoutShuru;
    private TextView idTvRight;
    private EditText idEdtCoupon;
    private TextView idTvClean;
    private String selectorStr,discountId;
    private Gson gson = new Gson();
    private String price;
    private String points_replace;
    private String fangfei;
    private boolean isflag = false;//是否手动输入
    private boolean isRecharge;
    private String end_price;
    public MemberCouponPopup(Activity context, String id,String selectorStr,String discountId,String price,String points_replace,String fangfei,boolean isRecharge,String end_price) {
        super(context);
        this.id = id;
        this.mContext = context;
        this.discountId = discountId;
        this.selectorStr = selectorStr;
        this.points_replace = points_replace;
        this.fangfei = fangfei;
        this.price = price;
        this.isRecharge = isRecharge;
        this.end_price = end_price;
        bindEvent();
    }
    public void setPopupDiscountSelector(PopupCouponSelector popupCouponSelector){
        this.popupCouponSelector = popupCouponSelector;
    }

    @Override
    protected Animation initShowAnimation() {
        return getTranslateAnimation(250 * 2, 0, 300);
    }

    @Override
    public View getClickToDismissView() {
        return popupView.findViewById(R.id.id_img_close);
    }

    @Override
    public View onCreatePopupView() {
        popupView = LayoutInflater.from(getContext()).inflate(R.layout.popup_member_coupon, null);
        return popupView;
    }

    @Override
    public View initAnimaView() {
        return popupView.findViewById(R.id.id_rlayout_bottom);
    }

    private void bindEvent() {
        initAdapter();
        if (popupView != null) {
            initView();
            idMultipLe.showLoading();
            idMultipLe.setOnRetryClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    initHttp();
                }
            });

            idListView.setAdapter(adapter);
            initClick();
            initHttp();
        }
    }

    private void initClick() {
        idListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (Float.parseFloat(end_price) >= list.get(position).getCoupon_full_price()){
                    if (StringUtils.isEmpty(list.get(position).getId())){
                        popupCouponSelector.selCoupon(false,"","","","0");
                        dismiss();
                    }else{
                        getPayment(list.get(position).getCoupon_no());
                    }
                }else{
                    MyToast.showShortToast(mContext,"优惠券不可用");
                }

            }
        });

        idRgpSelector.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                switch (checkedId){
                    case R.id.id_rb_fit:
                        idMultipLe.showLoading();
                        initHttp();
                        isflag = false;
                        idListView.setVisibility(View.VISIBLE);
                        idRlayoutShuru.setVisibility(View.GONE);
                        break;
                    case R.id.id_rb_member:
                        isflag = true;
                        idListView.setVisibility(View.GONE);
                        idRlayoutShuru.setVisibility(View.VISIBLE);
                        idMultipLe.showContent();
                        break;
                }
            }
        });

        idTvRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!StringUtils.isEmpty(idEdtCoupon.getText().toString())){
                    getPayment(idEdtCoupon.getText().toString());
                }else{
                    MyToast.showShortToast(mContext,"还未输入优惠券码!");
                }
            }
        });

        idTvClean.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupCouponSelector.selCoupon(false,"","","","0");
                dismiss();
            }
        });

    }

    private void initView() {
        ((TextView) popupView.findViewById(R.id.id_tv_type)).setText("优惠券");
        idListView = ((ListView) popupView.findViewById(R.id.id_listview));
        idMultipLe = ((MultipleStatusView) popupView.findViewById(R.id.id_multipleStatusView));
        idRlayoutShuru = ((RelativeLayout) popupView.findViewById(R.id.id_rlayout_diacount_shuru));
        idRgpSelector = ((RadioGroup) popupView.findViewById(R.id.id_rgp_selecotr));
        idTvRight = (TextView) popupView.findViewById(R.id.id_tv_right);
        idEdtCoupon = ((EditText) popupView.findViewById(R.id.id_edt_coupon_no));
        idTvClean = ((TextView) popupView.findViewById(R.id.id_tv_clean));
    }

    //获取优惠券
    private void initHttp() {
        HttpRequest.postUrl(Api.MEMBER_COUPON_SEARCH)
                .addParams("member_id",id)
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean checkCode = Utils.checkCode(mContext, json);
                        if (checkCode){
                            Gson gson = new Gson();
                            MemberCouponModel memberCouponModel = gson.fromJson(json, MemberCouponModel.class);
                            list.clear();
                            list.addAll(memberCouponModel.getData().getList());
                            adapter.notifyDataSetChanged();
                            if (list.size() > 0){
                                if (idMultipLe!= null){
                                    idMultipLe.showContent();
                                }
                            }else{
                                if (idMultipLe!= null){
                                    idMultipLe.showEmpty();
                                }
                            }
                        }else{
                            if (idMultipLe!= null){
                                idMultipLe.showEmpty();
                            }
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        if (idMultipLe!= null){
                            idMultipLe.showEmpty();
                        }
                    }
                });
    }

    private void initAdapter() {
        adapter = new CommonAdapter<MemberCouponModel.DataBean.ListBean>(mContext,R.layout.item_list_popup_discount,list) {
            @Override
            protected void convert(ViewHolder viewHolder, MemberCouponModel.DataBean.ListBean item, int position) {
                TextView idTvTypeName = viewHolder.getView(R.id.id_tv_type_name);
                TextView idtvtime = viewHolder.getView(R.id.id_tv_time);
                idTvTypeName.setText(Html.fromHtml(item.getCoupon_title() + "<br>" + item.getCoupon_content()));
                viewHolder.setText(R.id.id_tv_time,"有效期：" + item.getValidity_start() + "至" + item.getValidity_end());
                if (Float.parseFloat(end_price) >= item.getCoupon_full_price()){
                    idTvTypeName.setTextColor(mContext.getResources().getColor(R.color.wjx_content_txt_black_right));
                    idtvtime.setTextColor(mContext.getResources().getColor(R.color.wjx_content_txt_black_right));
                }else{
                    idTvTypeName.setTextColor(mContext.getResources().getColor(R.color.wjx_content_txt_grey));
                    idtvtime.setTextColor(mContext.getResources().getColor(R.color.wjx_content_txt_grey));
                }
            }
        };
    }

    //获取应支付金额
    private void getPayment(final String coupon_no) {
        if ("".equals(selectorStr)){
            HttpRequest.postUrl(Api.PAYMENT_AMOUNT_RECEIVABLES)
                    .addParams("price", price+"")
                    .addParams("discount_id", discountId)
                    .addParams("member_id", id)
                    .addParams("points_replace",points_replace)
                    .addParams("coupon_num", coupon_no)
                    .execute(new PostProcess.StringCallBack() {
                        @Override
                        public void onResponse(String json) {
                            boolean checkCode = Utils.checkCode(mContext, json);
                            if (checkCode) {
                                PaymentAmountModel paymentAmountModel = gson.fromJson(json, PaymentAmountModel.class);
                                PaymentAmountModel.DataBean.OrderInfoBean orderInfo = paymentAmountModel.getData().getOrderInfo();
                                if ("0".equals(orderInfo.getCoupon_price())){
                                    MyToast.showShortToast(mContext,"优惠券不存在或不可用");
                                }else{
                                    if (isflag){
                                        popupCouponSelector.selCoupon(true,idEdtCoupon.getText().toString(),idEdtCoupon.getText().toString()," "+orderInfo.getCoupon_price(),orderInfo.getPayment());
                                    }else{
                                        popupCouponSelector.selCoupon(true,coupon_no,coupon_no," "+orderInfo.getCoupon_price(),orderInfo.getPayment());
                                    }
                                    dismiss();
                                }
                            }
                        }

                        @Override
                        public void onError(Exception e) {

                        }
                    });
        }else{
            HttpRequest.postUrl( isRecharge?Api.CREATE_SELECTED_JICI_RECHARGE:Api.CREATE_SELECTED_GOODS)
                    .addParams("SelectedGoodsStr",selectorStr )
                    .addParams("coupon_num",coupon_no)
                    .addParams("discount_id",discountId)
                    .addParams("member_id",id)
                    .addParams("FangFei", fangfei)
                    .execute(new PostProcess.StringCallBack() {
                        @Override
                        public void onResponse(String json) {
                            boolean checkCode = Utils.checkCode(mContext, json);
                            if (checkCode) {
                                CreateSelectedGoodsModel createSelectedGoodsModel = gson.fromJson(json, CreateSelectedGoodsModel.class);
                                CreateSelectedGoodsModel.DataBean.OrderInfoBean orderInfo = createSelectedGoodsModel.getData().getOrderInfo();
                                if ("0".equals(orderInfo.getCoupon_price())){
                                    MyToast.showShortToast(mContext,"优惠券不存在或不可用");
                                }else{
                                    if (isflag){
                                        popupCouponSelector.selCoupon(true,idEdtCoupon.getText().toString(),idEdtCoupon.getText().toString()," "+orderInfo.getCoupon_price(),orderInfo.getPayment());
                                    }else{
                                        popupCouponSelector.selCoupon(true,coupon_no,coupon_no," "+orderInfo.getCoupon_price(),orderInfo.getPayment());
                                    }
                                    dismiss();
                                }
                            }
                        }
                        @Override
                        public void onError(Exception e) {

                        }
                    });

        }

    }

}
